﻿using System.Web.Mvc;
using System.Web.Security;
using OrderingPlatform.BllService.UserService;
using OrderingPlatform.Model.UserManage;
using OrderingPlatform.MvcExtension;

namespace OrderingPlatform.WebUI.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        private readonly  UserBaeService _userBaeService=new UserBaeService();

        public ActionResult LogOn(string returnUrl)
        {
            var model = new LogOnModel
            {
                ReturnUrl = returnUrl,
            };
            return View(model);
        }
        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
               
                var m = _userBaeService.CheckLogin(model);
                if (m.State == 1)
                {
                    FormsAuthentication.SetAuthCookie(model.UserCode, model.RememberMe);
                    var userModel=UserBaeService.GetUserModel(model.UserCode);
                    if (!string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return Redirect(model.ReturnUrl);
                    }
                    return RedirectToAction("Index", userModel.Category == ConstLibrary.CategoryCompanyName ? "CompanyManage" : "UserManage", new { area = "SystemManage" });
                }
                ModelState.AddModelError("", m.Message);
                return View(model);

            }
            return View(model);
        }

        public ActionResult Register(string category)
        {
            var model = new RegisterModel {Category = category};
            return View(model);
        }
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Password != model.ConfirmPassword)
                {
                    ModelState.AddModelError("ConfirmPassword", @"两次输入的密码不一致");
                    return View(model);
                }
                var m = _userBaeService.Register(model);
                if (m.State == 1)
                {
                    FormsAuthentication.SetAuthCookie(model.UserCode,false);
                    UserBaeService.GetUserModel(model.UserCode);
                    return RedirectToAction("Index", model.Category == ConstLibrary.CategoryCompanyName ? "CompanyManage" : "UserManage", new {area = "SystemManage"});
                }
                ModelState.AddModelError("", m.Message);
                return View(model);

            }
            return View(model);
        }

        public ActionResult LogOff()
        {
            UserBaeService.ClearUserCashe();
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home", new { area = "" });
        }
    }
}
